package com.yksj.healthtalk.ui.doctor;

import java.util.ArrayList;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import sfs2x.client.core.SFSEvent;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.yksj.healthtalk.adapter.DoctorAdapter;
import com.yksj.healthtalk.adapter.DoctorAdapter.onClickFriendAttentionListener;
import com.yksj.healthtalk.adapter.DoctorAdapter.onClickFriendHeadListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.friend.DoctorMainActivity;
import com.yksj.healthtalk.ui.friend.FriendHttpListener;
import com.yksj.healthtalk.ui.setting.PersonalInformationActivity;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 医生馆搜索列表
 * @author Administrator
 *
 */
public class DoctorSearchResultActivity extends BaseFragmentActivity implements OnRefreshListener2<ListView>,OnClickListener, onClickFriendHeadListener, OnItemClickListener, FriendHttpListener, onClickFriendAttentionListener{
	private Intent intent;
	int pageSize =1;
	int pageNum =20;
	private PullToRefreshListView mPullToRefreshListView;
	private ArrayList<CustomerInfoEntity> entities;
	private ListView mListView;
	private DoctorAdapter adapter;
	private AsyncHander mAsyncHander;
	private String duomeihao;
	private CustomerInfoEntity  mCustomerInfoEntity;
	private String DEFAUTPAGEMARK = "-100000";
	private String pageMark;
	private IntentFilter filter;
	private CustomerInfoEntity cacheCustomerInfoEntity;
	private AppData mAppData;
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_FRIEND)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(context, R.string.groupNewFail);
				} else {
					FriendHttpUtil.requestAttentionTofriendsResult(context,cacheCustomerInfoEntity, mAppData);
					adapter.notifyDataSetChanged();
				}
			} else if (action.equals(SFSEvent.CONNECTION_LOST)) {
			}
		}

	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.doctor_search_result);
		mAppData = HTalkApplication.getAppData();
		initWidget();
		initData();
	}

	private void initData() {
		mAsyncHander = new AsyncHander();
		entities = new ArrayList<CustomerInfoEntity>();
		adapter = new DoctorAdapter(this, entities, false);
		adapter.setonClickFriendAttentionListener(this);
		mListView.setAdapter(adapter);
		adapter.setonClickFriendHeadListener(this);
		mListView.addFooterView(LayoutInflater.from(getApplicationContext()).inflate(R.layout.list_line_layout, null));
		mListView.setFooterDividersEnabled(false);
		mListView.setEmptyView(getLayoutInflater().inflate(R.layout.listview_empty_view, null));
		intent = getIntent();
		duomeihao = null;
		if (intent.hasExtra("result")) {
			 duomeihao =   intent.getExtras().getString("result");
			 titleTextV.setText(duomeihao);
		}else if(intent.hasExtra("mCustomerInfoEntity")){
			mCustomerInfoEntity = (CustomerInfoEntity) intent.getExtras().get("mCustomerInfoEntity");
			 titleTextV.setText("搜索结果");
		}else {
			titleTextV.setText("");
		}
		
		if (!TextUtils.isEmpty(duomeihao)) {
			mPullToRefreshListView.setRefreshing();
			if (getIntent().hasExtra("merchantid")) {//三甲医院的专家列表的精确搜索
				RequestParams params = new RequestParams();
				params.put("customerId", SmartFoxClient.getLoginUserId());
				params.put("duomeihao", duomeihao);
				params.put("merchantId", getIntent().getExtras().getString("merchantid"));
				params.put("publicFlag", "1");
				params.put("pageSize", pageSize+"");
				params.put("pageNum", pageNum+"");
				HttpRestClient.doHttpFindMerchantDocByNameOrSpeciallyOrDuomei(params, mAsyncHander);
			}else {
				HttpRestClient.doHttpDoctorSearchResult(duomeihao, SmartFoxClient.getLoginUserId(), pageSize, pageNum, mAsyncHander);
			}
		}else if(mCustomerInfoEntity != null){//我的患者的搜索结果
			mPullToRefreshListView.setRefreshing();
			mListView.setAdapter(adapter);
			pageMark = DEFAUTPAGEMARK;
			mCustomerInfoEntity.setId(SmartFoxClient.getLoginUserId());
			mCustomerInfoEntity.setFlag(pageMark);
			FriendHttpUtil.getFriends(mCustomerInfoEntity, 0,DoctorSearchResultActivity.this);
		}
	
	}

	private void initWidget() {
		// TODO Auto-generated method stub
		initTitle();
		
		mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.hall);
		mListView = mPullToRefreshListView.getRefreshableView();
		
		mPullToRefreshListView.setOnRefreshListener(this);
		titleLeftBtn.setOnClickListener(this);
		mListView.setOnItemClickListener(this);
	}
	
	@Override
	public void onStop() {
		unRegisterReceiver(this);
		super.onStop();
	}
	
	@Override
	public void onStart() {
		registerReceiver(this);
		super.onStart();
	}
	
	
	public void registerReceiver(Context context) {
		filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		context.registerReceiver(receiver, filter);
	}

	public void unRegisterReceiver(Context context) {
		try {
			context.unregisterReceiver(receiver);
		} catch (Exception e) {
			System.err.println(e);
		}
	}
	
	
	class AsyncHander extends ObjectHttpResponseHandler {
		
		@Override
		public void onSuccess(int statusCode, Object response) {
			if (pageSize == 1) {
				entities.clear();
			}
			if (response != null && response instanceof ArrayList) {
				++pageSize;
				ArrayList<CustomerInfoEntity> infoEntities = (ArrayList<CustomerInfoEntity>) response;
				if (infoEntities.size() == 0) {
					ToastUtil.showToastPanl("暂无内容...");
				}else {
					entities.addAll(infoEntities);
					adapter.notifyDataSetChanged();
				}
				
			}else if(response != null && response instanceof String){
				if (pageSize == 1) {
					ToastUtil.showShort(getApplicationContext(), response.toString());
				}
			}
		}
		
		@Override
		public void onFinish() {
			mPullToRefreshListView.onRefreshComplete();
			super.onFinish();
		}

		@Override
		public Object onParseResponse(String content) {
			if (JsonParseUtils.filterErrorMessage(content) == null) {
				try {
					Object object = JSON.parse(content);
					if (object instanceof com.alibaba.fastjson.JSONObject) {
						if (((com.alibaba.fastjson.JSONObject) object).containsKey("CUSLIST")) {
							return FriendHttpUtil.jsonAnalysisFriendEntity(((com.alibaba.fastjson.JSONObject) object).getJSONArray("CUSLIST").toString(), false);
						}else if(((com.alibaba.fastjson.JSONObject) object).containsKey("list")){
							return FriendHttpUtil.jsonAnalysisFriendEntity(((com.alibaba.fastjson.JSONObject) object).getJSONArray("list").toString(), false);
						}
					}
					
				} catch (Exception e) {
					// TODO: handle exception
				}
			}else {
				return JsonParseUtils.filterErrorMessage(content);
			}
			return null;
			
		}		
	}


	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		pageSize = 1;
		if (!TextUtils.isEmpty(duomeihao)) {
			if (getIntent().hasExtra("merchantid")) {//三甲医院的专家列表的精确搜索
				RequestParams params = new RequestParams();
				params.put("customerId ", SmartFoxClient.getLoginUserId());
				params.put("duomeihao ", duomeihao);
				params.put("merchantId", getIntent().getExtras().getString("merchantid"));
				params.put("publicFlag", "1");
				params.put("pageSize", pageSize+"");
				params.put("pageNum", pageNum+"");
				HttpRestClient.doHttpFindMerchantDocByNameOrSpeciallyOrDuomei(params, mAsyncHander);
			}else {
				HttpRestClient.doHttpDoctorSearchResult(duomeihao, SmartFoxClient.getLoginUserId(), pageSize, pageNum, mAsyncHander);
			}
		}else if(mCustomerInfoEntity != null){
			pageMark = DEFAUTPAGEMARK;
			mCustomerInfoEntity.setId(SmartFoxClient.getLoginUserId());
			mCustomerInfoEntity.setFlag(pageMark);
			FriendHttpUtil.getFriends(mCustomerInfoEntity, 0,DoctorSearchResultActivity.this);
		}
	}

	/**
	 * 关注 取消关注 回调
	 */
	@Override
	public void onClickFriendAttention(int attentioned,
			CustomerInfoEntity entity, int positon) {
		cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(this,null, entity);
	}
	
	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		if (!TextUtils.isEmpty(duomeihao)) {
			if (getIntent().hasExtra("merchantid")) {//三甲医院的专家列表的精确搜索
				RequestParams params = new RequestParams();
				params.put("customerId ", SmartFoxClient.getLoginUserId());
				params.put("duomeihao ", duomeihao);
				params.put("merchantId", getIntent().getExtras().getString("merchantid"));
				params.put("publicFlag", "1");
				params.put("pageSize", pageSize+"");
				params.put("pageNum", pageNum+"");
				HttpRestClient.doHttpFindMerchantDocByNameOrSpeciallyOrDuomei(params, mAsyncHander);
			}else {
				HttpRestClient.doHttpDoctorSearchResult(duomeihao, SmartFoxClient.getLoginUserId(), pageSize, pageNum, mAsyncHander);
			}
		}else if(mCustomerInfoEntity != null){
			mCustomerInfoEntity.setId(SmartFoxClient.getLoginUserId());
			mCustomerInfoEntity.setFlag(pageMark);
			FriendHttpUtil.getFriends(mCustomerInfoEntity, 0,DoctorSearchResultActivity.this);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		}
	}

	/**
	 * 点击头像查看资料
	 */
	@Override
	public void onClickFriendHead(CustomerInfoEntity entity, int positon) {
		if (SmartFoxClient.getLoginUserId().equals(entity.getId())) {
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), PersonalInformationActivity.class);
			startActivity(intent);
		}else {
			Intent intent = new Intent(getApplicationContext(), DoctorMainActivity.class);
			intent.putExtra("id", entity.getId());
			startActivity(intent);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		if (0<arg2 && arg2 <= entities.size()) {
			CustomerInfoEntity entity = entities.get(arg2-1);
			if (SmartFoxClient.getLoginUserId().equals(entity.getId())) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), PersonalInformationActivity.class);
				startActivity(intent);
			}else {
				Intent intent = new Intent(getApplicationContext(), DoctorMainActivity.class);
				intent.putExtra("id", entity.getId());
				startActivity(intent);
			}
		}
	}


	@Override
	public void responseSuccess(int type, int sourceType,
			ArrayList<CustomerInfoEntity> c) {
		mPullToRefreshListView.onRefreshComplete();
		entities.addAll(c);
		adapter.notifyDataSetChanged();
		pageMark = adapter.getPageMark(false);
	}

	@Override
	public void responseError(int type, int sourceType, String content) {
		mPullToRefreshListView.onRefreshComplete();
	}

}
